using FrameWork;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using lhservice.common;
using System.Net.Http;
using System.Text;
using System.Net;
using Microsoft.AspNetCore.Http;
using lhservice.common.websocket;
using DBEntitie;
using lhservice.Models;

namespace lhservice.Controllers
{
#pragma warning disable IDE1006
  public class PayOrderInfo_amount
  {
    public long total { set; get; }
    public string currency { set; get; }
  }
  public class PayOrderInfo_payer
  {
    public string openid { set; get; }
  }
  public class PayOrderInfo
  {
    public string mchid { set; get; }
    public string out_trade_no { set; get; }
    public string appid { set; get; }
    public string description { set; get; }
    public string notify_url { set; get; }
    public PayOrderInfo_amount amount { set; get; }
    public PayOrderInfo_payer payer { set; get; }
  }
  public class SubmitPayOrder
  {
    public string codes { set; get; }
    public long total { set; get; }
    public string description { set; get; }
    public string out_trade_no { set; get; }
  }

#pragma warning restore IDE1006

  [Authorize]
  [ApiController]
  [Route("api/[controller]")]
  [AllowAnonymous]
  public class PayController : TimController
  {

    [AllowAnonymous]
    [HttpGet("[action]")]
    public async Task<IActionResult> GetOpenid(string codes)
    {
      var appid = WxPayHelper.appid;
      var secret = WxPayHelper.secret;
      var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={codes}&grant_type=authorization_code";
      var client = new HttpClient();
      var res = await client.GetStringAsync(url);
      Dictionary<string, dynamic> _res = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(res);
      return await PublicTool.ReturnSuccess(_res["openid"]);
    }


    [HttpPost("[action]"), HttpGet("[action]")]
    public async Task<IActionResult> PayEcho()
    {
      string result = string.Empty;
      try
      {
        Request.EnableBuffering();
        using (var reader = new StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
        {
          result = await reader.ReadToEndAsync();
          Request.Body.Position = 0;//以后可以重复读取
        }
      }
      catch (Exception) { }


      Response.StatusCode = (int)HttpStatusCode.OK;
      return await PublicTool.ReturnSuccess("");
    }

    [HttpGet("[action]")]
    public async Task<IActionResult> PayTest()
    {
      HttpClient client = new HttpClient(new WxPayHelper());
      var response = await client.GetAsync("https://api.mch.weixin.qq.com/v3/certificates");
      var _res = await response.Content.ReadAsStringAsync();
      return await PublicTool.ReturnSuccess(_res);
    }

    [HttpPost("[action]")]
    public async Task<IActionResult> CreatePayOrder([FromBody] SubmitPayOrder Model)
    {
      // 1、凭前端提交的codes请求openid
      string api = $"https://api.weixin.qq.com/sns/jscode2session?appid={WxPayHelper.appid}&secret={WxPayHelper.secret}&js_code={Model.codes}&grant_type=authorization_code";
      var res = await new HttpClient().GetStringAsync(api);
      Dictionary<string, dynamic> _res = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(res);
      string openid = _res["openid"];

      WxPayHelper _helper = new WxPayHelper();
      HttpClient client = new HttpClient(_helper);
      api = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";

      // 2、构造订单
      PayOrderInfo payOrderInfo = new PayOrderInfo()
      {
        amount = new PayOrderInfo_amount() { total = Model.total *100, currency = "CNY" },
        payer = new PayOrderInfo_payer() { openid = openid },
        mchid = _helper.merchantId,
        out_trade_no = Model.out_trade_no,
        appid = WxPayHelper.appid,
        description = Model.description,
        notify_url = WxPayHelper.notify_url
      };

      HttpContent content = new StringContent(JsonConvert.SerializeObject(payOrderInfo), Encoding.UTF8, "application/json");
      var response = await client.PostAsync(api, content);
      var __res = response.Content.ReadAsStringAsync();
      var ___res = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(__res.Result);

      // 3、二次签名
      var paySign = _helper.GetPaySign(___res["prepay_id"]);
      return await PublicTool.ReturnSuccess(paySign);
    }

    [HttpGet("[action]")]
    public async Task<IActionResult> QueryPayOrder(string transaction_id = "", string out_trade_no = "")
    {
      WxPayHelper _helper = new WxPayHelper();
      HttpClient client = new HttpClient(_helper);
      string api = "";

      api = transaction_id == "" ? $"https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/{out_trade_no}?mchid={_helper.merchantId}"
        : $"https://api.mch.weixin.qq.com/v3/pay/transactions/id/{transaction_id}?mchid={_helper.merchantId}";

      var response = await client.GetAsync(api);
      var _res = response.Content.ReadAsStringAsync();
      return await PublicTool.ReturnSuccess(_res.Result);
    }

    [HttpPost("[action]")]
    public async void SuccessPay([FromBody] Dictionary<string, string> data)
    {
      //1、更新支付状态
      var _pagePath = data["p"];
      Dictionary<string, dynamic> _msg;
      string sid, oid;
      using (var db = new SyBaseEntities())
      {
        string sql = $"update z_service_msg set State= 1 where PagePath='{_pagePath}'";
        db.Execute(sql);
        sql = $"select * from z_service_msg where PagePath='{_pagePath}'";
        _msg = db.QueryTable(sql).ToList()[0];
        sid = _msg["SessionId"].ToString();
        oid = _msg["OrderNum"].ToString();     
      }

      //2、发送成功通知
      var clients = WebsocketClientCollection.GetClientList(sid);
      await WebsocketClientCollection.SendMessageToClientList(clients, "successPay", JsonConvert.SerializeObject(_msg));

    }



    [HttpGet("[action]")]
    public async Task<IActionResult> ClosePayOrder(string out_trade_no)
    {
      WxPayHelper _helper = new WxPayHelper();
      HttpClient client = new HttpClient(_helper);
      string api = $"https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/{out_trade_no}/close";
      var _body = new Dictionary<string, string> { ["mchid"] = _helper.merchantId };
      HttpContent content = new StringContent(JsonConvert.SerializeObject(_body), Encoding.UTF8, "application/json");
      var response = await client.PostAsync(api, content);
      var _res = response.Content.ReadAsStringAsync();
      return await PublicTool.ReturnSuccess(_res);
    }
  }
}
